const glados = async (cookie,user='未定义') => {
  // const cookie = process.env.GLADOS;
  if (!cookie) return;
  try {
    const headers = {
      cookie: cookie,
      referer: "https://glados.rocks/console/checkin",
      "user-agent": "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)",
    };
    const checkin = await fetch("https://glados.rocks/api/user/checkin", {
      method: "POST",
      headers: { ...headers, "content-type": "application/json" },
      body: `{"token":"${process.env.TOKEN || "glados.one"}"}`,
    }).then((r) => r.json());
    const status = await fetch("https://glados.rocks/api/user/status", {
      method: "GET",
      headers,
    }).then((r) => r.json());
    return [
      `[${user}]签到${checkin?.list ? "OK" : "fail"}(剩余 ${Number(
        status.data.leftDays
      )})`,
      `${checkin.message}`,
      `Left Days ${Number(status.data.leftDays)}`,
    ];
  } catch (error) {
    console.log(error)
    return [
      "["+user+"]Checkin Error",
      `${error}`,
      `<${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}>`,
    ];
  }
};

const notify = async (contents, token) => {
  console.log(contents)
  // const token = process.env.NOTIFY;
  if (!token || !contents) return;
  await fetch(`https://www.pushplus.plus/send`, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({
      token,
      title: contents[0],
      content: contents.join("<br>"),
      template: "markdown",
    }),
  });
};

const main = async () => {
  // 获取几个菜单
  const GLADOSS = getStrObj(process.env.GLADOS);
  const USERS = getStrObj(process.env.USERS);
  const NOTIFYS = getStrObj(process.env.NOTIFY);
  // cookies.split(";").forEach
  await Promise.all(
    GLADOSS.map(async (v, i) => notify(await glados(v,USERS[i]), NOTIFYS[i]))
  );
  console.log("执行完成");
};

function getStrObj(str) {
  try {
    const res = new Function(`return ${str}`)();
    if (!Array.isArray(res)) {
      return [res];
    }
    return res;
  } catch (e) {
    return [];
  }
}

main();
